package com.lct.simpleforecast.mvp.presenter

import com.lct.simpleforecast.bean.CityBean
import com.lct.simpleforecast.mvp.model.SettingModel
import com.lct.simpleforecast.mvp.model.network.IRequest
import com.lct.simpleforecast.mvp.presenter.base.BasePresenter
import com.lct.simpleforecast.mvp.view.ISettingView
import okhttp3.Call

/**
 * Author：SkySmile
 * Date：2018/7/12
 * Description：SettingActivity对应的presenter
 */
class SettingPresenter : BasePresenter<ISettingView>() {
    private val model = SettingModel()
    private var call: Call? = null

    /**
     * 获取城市数据
     *
     * @param searchKey 搜索关键字
     */
    fun getCityData(searchKey: String) {
        view?.showLoading()
        call = model.getCityData(searchKey, object : IRequest<CityBean> {
            /**
             * 网络不可用
             */
            override fun onNetworkError() {
                view?.onNetWorkError()
            }

            /**
             * 请求成功
             */
            override fun onSuccess(t: CityBean) {
                if (t.status() == "ok") {
                    view?.hideLoading()
                    view?.onLoadSuccess(t)
                } else {
                    view?.onLoadFailure(t.status())
                }
            }

            /**
             * 请求失败
             */
            override fun onFailure(errorMsg: String) {
                view?.onLoadFailure(errorMsg)
            }
        })
    }

    override fun detachView() {
        super.detachView()
        call?.cancel()
    }
}